import request_send
import lxml.etree as etree
import json
import os
import time as Time


url = "https://www.xmwav.com/"

hearders = {
    "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Mobile Safari/537.36 Edg/122.0.0.0"
}

response = request_send.send_request(url, headers=hearders)

tree = etree.HTML(response)

classify = tree.xpath('//ul[@class="clearfix zh"]//li/a')

classify_data = [(item.text, item.get("href")) for item in classify]

for i, (text, href) in enumerate(classify_data, start=1):
    print(f"{i},{text},{href}")

choice = int(input("请输入你想要的资源分类的序号："))

if 1 <= choice <= len(classify_data):
    classify_link = classify_data[choice - 1][1]
    print(f"你选择的是:{classify_data[choice-1][0]}，链接是{classify_link}")

else:
    print("序号错误")


# 第二部分：获取资源页面链接
# 把资源页面链接保存到json文件中，方便下次直接读取


json_file = os.path.join(
    "resources", "xiongmao_music_data", "links", f"{classify_data[choice-1][0]}.json"
)

# 创建文件的目录
os.makedirs(os.path.dirname(json_file), exist_ok=True)

page_next_link2 = classify_link

while page_next_link2:

    response = request_send.send_request(classify_link, headers=hearders)

    tree = etree.HTML(response)

    # 先处理简单的
    link_elements = tree.xpath('//div[@class="list bgb "]/ul//a')

    resources_link = [(item.get("title"), item.get("href")) for item in link_elements]

    # 处理分页
    page_next_link1 = "".join(
        tree.xpath('//ul[@class="pagination"]/li[last()]/a/@href')
    )

    if page_next_link1:
        page_next_link2 = "https://www.xmwav.com" + page_next_link1
    else:
        page_next_link2 = None

    resources_link_dict = {title: link for title, link in resources_link}

    with open(json_file, "w", encoding="utf-8") as f:
        json.dump(resources_link_dict, f, ensure_ascii=False, indent=4)

    Time.sleep(2)
